package com.imooc.order.controller;

import com.imooc.order.client.ProductClient;
import com.imooc.order.dataobject.ProductInfo;
import com.imooc.order.dto.CartDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: JLL
 * @Date: 2019/5/4 23:03
 */
@RestController
@Slf4j
public class ClientController {


    @Autowired
    private ProductClient productClient;


//    @Autowired
//    private LoadBalancerClient loadBalancerClient;

//    @Autowired
//    private RestTemplate restTemplate;  //因为已经@Bean，配置进来了，可以直接注入，不用new

    @GetMapping(value = "/getProductMsg")
    public String getProductMsg(){
        //1.第一种方式（直接使用restTemplate、url写死）
//        RestTemplate restTemplate = new RestTemplate();
//        String responese = restTemplate.getForObject("http://localhost:8081/msg",String.class);

        //2.第二种方式（使用LoadBalancerClient，通过应用名PRODUCT，获取host和port，再拼接url，再用rtl）
        RestTemplate restTemplate = new RestTemplate();
        //选择服务名，返回的是一个服务实例
//        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
//        String url = String.format("http://%s:%s", serviceInstance.getHost(),serviceInstance.getPort())+ "/msg";
//        String responese  = restTemplate.getForObject( url,String.class);


        //3.第三种方式（利用@LoadBalanced，可在rtl里使用 应用名PRODUCT ）
        String responese  = restTemplate.getForObject( "http://PRODUCT/msg",String.class);
        log.info("response = {}", responese);
        return responese;
    }

    @GetMapping(value = "/getProductMsgFeign")
    public String getProductMsgFeign(){
        String response  =  productClient.productMsg();
        log.info("response = {}", response);
        return response;
    }


    @GetMapping(value = "/getProductListFeign")
    public String getProductListFeign(){
        List<ProductInfo> productInfoList = productClient.listForOrder(Arrays.asList("157875196366160022","157875227953464068"));
        log.info("productInfoList = {}", productInfoList);
        return "ok";
    }

    @GetMapping(value = "/decreaseStockFeign")
    public String decreaseStockFeign(){
        CartDTO cartDTO = new CartDTO("157....XXXX",3);
        productClient.decreaseStock(Arrays.asList(cartDTO));
        return "ok";
    }


}
